<template>
  <div class="ui form">
    <div class="fields inline">
      <label>添加属性（销售属性）</label>
      <div class="field">
        <div class="ui icon input" @keyup.enter="searchAttr" :class="{loading: searchLoading, disabled: searchLoading}">
          <input type="text" v-model="name" placeholder="输入关键字">
          <i class="search icon link" @click="searchAttr"></i>
        </div>
      </div>
      <t-select :data="attrOptions" @onchange="attrChange" v-if="searchList.length>0"></t-select>
    </div>

    <!-- <div class="field inline">
      <div class="ui action input">
        <input type="text" placeholder="输入关键字" v-model="name">
        <div class="ui button secondary" @click="searchAttr" :class="{loading: searchLoading, disabled: searchLoading}">搜索</div>
      </div>
    </div>
    <div class="filed" v-if="searchList.length>0">
      <ul class="search-items">
        <li v-for="(attr, index) in searchList" class="search-items-item"  @click="selectAttr(attr, 'unitList')">{{attr.title}}</li>
      </ul>
    </div> -->
    <div class="filed">
      <t-table
      :data="show_unitList"
      placeholder="暂无数据"
      @onchange="selAttrChange"
      @onclickBtn="onclickBtn"
      tableName="unitList"
      :columns='[
      {buttons:
        {
          label: "排序",
          btns: [{
            name: "up",
            label: "上移"
          },{
            name: "down",
            label: "下移"
          }]
        }
      },
      {buttons:
        {
          label: "操作",
          btns: [{
            name: "edit",
            label: "编辑"
          },{
            name: "delete",
            label: "删除",
          }]
        },
      },
      {filed:"id", label:"商品属性ID"},
      {filed:"title", label:"属性名称"},
      {filed:"value", label:"属性值", default:"--"},
      {filed:"allow_custom_name", label:"自定义属性值"},
      /*{filed:"is_must_str", label:"信息填写"}*/
      ]'>
    </t-table>
  </div>
  <div class="field inline">
    <label>搜索不到需要的属性？</label>
    <button class="ui compact icon button secondary" @click="applyNew">
      <i class="plus icon"></i>申请创建属性
    </button>
  </div>
  <div class="filed">
    <t-table
    :data="show_applyUnit"
    placeholder="暂无数据"
    tableName="applyUnit"
    @onclickBtn="onclickBtn"
    :columns='[
      {buttons:{
        label: "操作",
        btns: [{
          name: "edit",
          label: "编辑"
        }]
      }
    },
    {filed:"id", label:"商品属性ID"},
    {filed:"name", label:"属性名称"},
    {filed:"show_type_name", label:"显示形式"},
    {filed:"value", label:"属性值", default:"--"},
    ]'>
  </t-table>
  </div>
<!-- <t-Pop :page="componentName" @onhide="hidePop" @onshow="showPop" @onchange="onchange" @onsubmit="onsubmit" @oncancel="oncancel" :data="popData" :title="popTitle" :active="isshow"></t-Pop> -->
  <t-editcom v-if="componentName== 'editCom'" @onchange="onchange" @oncancel="oncancel" :otherEdit="true" otherEdit_mid="91" @dosth="onsubmit" :data="popData" :title="popTitle" :withPop="1==1" :active="isshow"></t-editcom>
  <t-field v-else @onchange="onchange" @oncancel="oncancel" :otherEdit="true" otherEdit_mid="91" @onsubmit="onsubmit" :data="popData" :title="popTitle" :withPop="1==1" :active="isshow"></t-field>
</div>
</template>
<script>
  import tool from 'src/util/tool';
  import util from '_util/index';
  import logic from '_logic';

  import tTable from 'components/tunit/tTable';

  import tEditcom from 'components/tunit/editCom'
  import tField from 'components/tunit/tFields'
  import tSelect from 'components/tunit/fields/enum'

  export default {
    data() {
      return {
        val: null,
        name: "",
        searchLoading: false,
        searchList:[],
        unitList:[],
        show_unitList:[],
        applyUnit:[],
        show_applyUnit:[],
        popData:null,
        isshow: false,
        popTitle:"",
        componentName:"",
        maxNum: 5,
        inEdit:{
          name: "",
          data: null
        },
        attrOptions:{
          placeholder:"请选择属性",
          show_type: "select",
          filter: true,
          name: "selAttr",
          value:"",
          element: []
        }
      }
    },
    components:{
      tTable,
      tEditcom,
      tField,
      tSelect,
    },
    methods: {
      /* 数据操作 */
      getData({url=[], data={}, callback=null, error=false, msg=null}){
        url = tool.getApi(this, url[0], url[1]);
        util.http.SR(this, url, data, msg, callback, error);
      },
      hidePop(){
        this.isshow = false;
      },
      showPop(){
        this.isshow = true;
      },
      /* 申请 */
      applyNew(){
        this.resetInEdit();
        this.componentName = "editCom";
        this.inEdit.name = "applyUnit";
        this.inEdit.data = {};
        this.showPop();
      },
      doApply(val={}){
        let url = tool.getApi(this, 'Pattr', 'insert'),
        _this = this;
        val._need_back = 1;
        val.is_apply = 1;
        this.getData({
          url: ['Pattr', 'insert'],
          data: val,
          msg: "添加成功",
          callback(rs){
            val.id = rs.id;
            _this.searchList = rs;
            _this.hidePop();
            _this.doAddData('applyUnit', Object.assign(rs.back_data, {id: rs.id}));
          }
        })
      },
      /*返回 true 为 添加成功， 返回false 为更新成功*/
      doAddData(listName, data){
        let isExsist = false;
        this[listName].forEach((item) => {
          if(item.id == this.inEdit.data.id || item.id == data.id){
            isExsist = true;
            item = Object.assign(item, data);
          }
        });
        if(!isExsist){
          this[listName].unshift(  Object.assign({}, this.inEdit.data, data) );
        }
        this.UpdateSort( this[listName], listName );
        this.resetInEdit();
        return !isExsist;
      },
      searchAttr(){
        let _this =this;
        this.searchLoading = true;
        this.getData({
          url: ['Pattr', 'getAttr'],
          data: {name: this.name, type: 1},
          callback(rs){
            _this.searchList = rs;
            _this.searchLoading = false;
          },
          error(){
            _this.searchLoading = false;
          }
        })
      },
      /*选择 属性*/
      attrChange({value}){
        if(!value){return}
        this.attrOptions.value = value;
        this.selectAttr( this.searchList.filter((item)=>{
          return item.id == value;
        })[0] , 'unitList');
      },
      /*选择 属性*/
      selectAttr(attr, name){
        let isExsist = false;
        this.componentName = "";
        this.unitList.forEach((item) => {
          if(!isExsist){
            isExsist = item.id == attr.id;
          }
        });
        if(isExsist ){
          util.showMsg(this, 'success', `属性[${attr.title}]已存在`)
          return;
        }
        if(this.unitList.length == this.maxNum){
          util.showMsg(this, 'error', `最多添加${this.maxNum}个属性`)
          return;
        }
        this.attr2popData(attr, name);

      },
      attr2popData(attr, name){
        this.inEdit.name = name
        this.inEdit.data = JSON.parse( JSON.stringify(attr) );
        this.popTitle = this.inEdit.data.title + "-ID:" + this.inEdit.data.id;
        if(name == "applyUnit"){
          util.store.commit(this,'set_otherEdit_op', 'update');
          util.store.commit(this,'setOtherEditVo',  attr);
          this.componentName = "editCom";
        }
        if(name == "unitList"){
          this.popData = [{
            label: "显示形式",
            readonly: true,
            value: this.inEdit.data.show_type_name
          },{
            label: "描述",
            show_type: "textarea",
            readonly: true,
            name: "introduction",
            value: attr.introduction
          },{
            label: "属性值",
            // show_type_code: this.inEdit.data.show_type,
            show_type_code: this.inEdit.data.show_type,
            readonly: true,
            name: "value",
            value: "",
            element: this.inEdit.data.value
          },
		  // {
          //   label: "信息填写",
          //   show_type: "select",
          //   readonly: true,
          //   name: "is_must",
          //   value: 1,
          //   element: [{label:"必填", value:1 },{label: "选填", value:0}]
          // }
	  ];
        }
        this.isshow = true;
      },
      UpdateSort(arr, tableName){ /*更新排序*/
        this.$emit("onchange", {name: tableName, data: arr});
        arr.forEach((item, i) => {
          item.sort = i;
        });
        this["show_"+ tableName] = JSON.parse( JSON.stringify( this[tableName] ) ).map((item)=>{
          item.is_must_str = item.is_must == 1 ? "必填" : "非必填";
          return item;
        });
      },
      onclickBtn({type, rowIndex, tableName}){
        /*up, down, edit, delete*/
        switch(type){
          case "up":
          this[tableName][rowIndex] = this[tableName].splice(rowIndex-1, 1,  this[tableName][rowIndex])[0];
          this.UpdateSort( this[tableName], tableName);
          break;
          case "down":
          this[tableName][rowIndex] = this[tableName].splice(rowIndex+1, 1,  this[tableName][rowIndex])[0];
          this.UpdateSort( this[tableName], tableName);
          break;
          case "edit":
          this.attr2popData( this[tableName][rowIndex], tableName);
          break;
          case "delete":
          this[tableName].splice(rowIndex, 1);
          this.UpdateSort( this[tableName], tableName);
          break;
        }
      },
      onchange({name, value}){
       /*this.inEdit[name] = value;*/
     },
     onsubmit(form){
      if(this.inEdit.name =="applyUnit"){
        this.doApply(form);
        return
      }
      this.doAddData(this.inEdit.name, form);
      this.hidePop();
    },
    oncancel(){
      this.hidePop();
      this.resetInEdit()
    },
    resetInEdit(){
      this.componentName = "";
      this.inEdit.name = "";
      this.inEdit.data = null;
      util.store.commit(this,'setOtherEditVo', {});
      util.store.commit(this,'set_otherEdit_op', '');
    },
    selAttrChange(val){
      this.unitList = val;
    }
  },
  props: {
    data:{
      type: Object,
      default: function(){
        return {}
      }
    }
  },
  watch:{
    searchList(val=[]){
      this.attrOptions.element.length = 0;
      val.forEach((item) => {
        let {id, type_name, title, introduction=""} = item;
        this.attrOptions.element.push({
          label: title,
          value: id,
          description: introduction
        });
      })
    }
  },
  created() {
    let _this = this;
    ["unitList", "applyUnit"].forEach((attr) => {
      if(this.data[attr]){
        this.data[attr].sort((a, b)=>{
          return a.sort> b.sort;
        });
        this[attr] = this.data[attr];
        this.UpdateSort(this[attr], attr);
      }
    });
  },
}
</script>
<style scoped lang="less">
  .ui.form .filed{
    margin-bottom: 10px;
  }
  .ui.table{
    width: auto
  }
  .search-items{
    max-height: 100px;
    width: 250px;
    border:1px solid rgba(34,36,38,.1);
    overflow: auto;
    padding: 0;
    &-item{
      margin: 0;
      padding: 0;
      list-style: none;
      padding: 10px;
      font-size: 12px;
      &:hover{
        background-color: rgba(34,36,38,.1)
      }
    }
  }
</style>
